package cn.mrlong.base.extensions

import java.text.DecimalFormat
import java.text.NumberFormat

/**
 * 作者：BINGO
 * 时间：2021/03/29 10:52
 */
class Size {
    companion object {
        private const val SPACE_KB = 1024.0
        private const val SPACE_MB = 1024 * SPACE_KB
        private const val SPACE_GB = 1024 * SPACE_MB
        private const val SPACE_TB = 1024 * SPACE_GB

        /**
         *将byte格式kb,mb,gb,tb
         * @param sizeInBytes Long 单位byte
         * @return String?
         */
        fun bytes2String(sizeInBytes: Long): String? {
            val nf: NumberFormat = DecimalFormat()
            nf.maximumFractionDigits = 2
            return try {
                if (sizeInBytes < SPACE_KB) {
                    nf.format(sizeInBytes) + " B"
                } else if (sizeInBytes < SPACE_MB) {
                    nf.format(sizeInBytes / SPACE_KB) + " KB"
                } else if (sizeInBytes < SPACE_GB) {
                    nf.format(sizeInBytes / SPACE_MB) + " MB"
                } else if (sizeInBytes < SPACE_TB) {
                    nf.format(sizeInBytes / SPACE_GB) + " GB"
                } else {
                    nf.format(sizeInBytes / SPACE_TB) + " TB"
                }
            } catch (e: Exception) {
                "$sizeInBytes B"
            }
        }
    }
}